package com.gr.staffpm.pages.profile;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.joda.time.Instant;
import org.wicketstuff.annotation.mount.MountPath;
import org.wicketstuff.annotation.strategy.MountHybrid;

import com.gr.staffpm.StaffPMWebPage;
import com.gr.staffpm.datatypes.User;
import com.gr.staffpm.pages.behaviour.FocusOnLoadBehavior;
import com.gr.staffpm.security.service.UserService;
import com.gr.staffpm.user.changepassword.ChangePasswordPanel;

@MountHybrid
@MountPath(path = "secure/ViewProfile")
public class ViewProfile extends StaffPMWebPage {

    @SpringBean(name = "userService")
    private UserService userService;
    private final User currentUser;
    private final TextField<String> firstName;
    private final TextField<String> lastName;
    private final TextField<String> emailAddress;
    private final AjaxCheckBox gcalEnabled;
    private final GCalOAuthPanel gcalOAuth = new GCalOAuthPanel("gcalOAuth", userService);
    private final ModalWindow changePasswordWindow;

    public ViewProfile() {
        super();
        currentUser = userService.getCurrentUser();
        super.onBeforeRender();
        add(new Label("pageHeaderText", "Profile: " + currentUser.getUsername()));
        add(new FeedbackPanel("feedback"));

        final Form<User> editUserForm = new Form<User>("editUserForm", new CompoundPropertyModel<User>(currentUser));

        firstName = new TextField<String>("firstName");
        firstName.add(new FocusOnLoadBehavior());
        firstName.setRequired(true);
        editUserForm.add(firstName);

        lastName = new TextField<String>("lastName");
        lastName.setRequired(true);
        editUserForm.add(lastName);

        editUserForm.add(new AjaxButton("changePassword") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                launchChangePasswordWindow(target);
            }

        });

        emailAddress = new TextField<String>("emailAddress");
        emailAddress.add(EmailAddressValidator.getInstance());
        emailAddress.setRequired(true);
        editUserForm.add(emailAddress);

        editUserForm.add(changePasswordWindow = new ModalWindow("changePasswordWindow"));

        changePasswordWindow.setInitialHeight(200);
        changePasswordWindow.setInitialWidth(380);
        changePasswordWindow.setContent(new ChangePasswordPanel(changePasswordWindow.getContentId(), userService, currentUser, changePasswordWindow));
        changePasswordWindow.setTitle("Change User Password");
        changePasswordWindow.setCookieName("change-user-password");

        gcalEnabled = new AjaxCheckBox("gcalEnabled") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                gcalOAuth.setVisible(!gcalOAuth.isVisible());
                target.addComponent(editUserForm);
            }

        };
        gcalEnabled.setOutputMarkupId(true);
        gcalOAuth.setOutputMarkupId(true);
        editUserForm.add(gcalEnabled);
        editUserForm.add(gcalOAuth);

        editUserForm.add(new AjaxButton("saveButton") {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {

                currentUser.setFirstName(firstName.getValue());
                currentUser.setLastName(lastName.getValue());
                currentUser.setEmailAddress(emailAddress.getValue());
                currentUser.setGcalEnabled(Boolean.parseBoolean(gcalEnabled.getValue()));
                currentUser.setLastUpdated(new Instant().toDate());
                currentUser.setUpdatedBy(currentUser);
                if (!gcalOAuth.getEmail().getValue().isEmpty())
                    gcalOAuth.submit(target);

                userService.addOrUpdateUser(currentUser);
            }

        });

        add(editUserForm);
    }

    @Override
    public String getTitle() {
        return "User Profile: " + currentUser.getUsername() + " StaffPM";
    }

    protected void launchChangePasswordWindow(AjaxRequestTarget target) {
        changePasswordWindow.show(target);
    }

}
